package com.todo.dao;

import java.util.List;
import java.util.Random;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.todo.model.Task;

@Repository
public class TaskDao implements ITaskDao {

    @Autowired
    private SessionFactory sessionFactory;

    // @Transactional
    public void addTask(Task task) {
        // TODO task#16
        int generatedId = (new Random()).nextInt();
        task.setId(Math.abs(generatedId));

        // TODO task#17
        Session session = sessionFactory.openSession();
        try {
            session.save(task);
        } finally {
            session.flush();
            session.close();
        }
    }

    @SuppressWarnings("unchecked")
    public List<Task> listTask() {
        // TODO task#17
        Session session = sessionFactory.openSession();
        try {
            return session.createQuery("from Task").list();
        } finally {
            session.flush();
            session.close();
        }
    }

    public void updateTask(Task task) {
        // TODO task#17
        Session session = sessionFactory.openSession();
        try {
            session.save(task);
        } finally {
            session.flush();
            session.close();
        }
    }

    public void removeTask(int id) {
        // TODO task#17
        Session session = sessionFactory.openSession();
        try {
            Task task = (Task) session.load(Task.class, id);
            session.delete(task);
        } finally {
            session.flush();
            session.close();
        }
    }

}
